package com.chen.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.alicloud.sms.ISmsService;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.domain.Sms;
import com.chen.mapper.SmsMapper;
import com.chen.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements SmsService {

    @Resource
    private ISmsService smsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void sendTo(Sms sms) {

        SendSmsRequest sendSmsRequest = buildSmsRequest(sms);
        try {
            smsService.sendSmsRequest(sendSmsRequest);
        } catch (ClientException e) {
            log.info("发送短信失败");
            e.printStackTrace();
        }
    }

    /**
     * 构造短信请求对象
     *
     * @param sms
     * @return
     */
    private SendSmsRequest buildSmsRequest(Sms sms) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(sms.getMobile()); //发送给谁

        //查询后台配置
        sendSmsRequest.setSignName("123456"); // 设置签名---公司里面不会随便的改变--Config 查询签名
        sendSmsRequest.setTemplateCode("123445"); // 模板的Code--动态改变

        //生成随机数
        String code = RandomUtil.randomNumbers(6);
        // 需要把code 保存到redis 里面
        redisTemplate.opsForValue().set("SMS:" + sms.getTemplateCode() + ":" + sms.getMobile(), code, 1, TimeUnit.MINUTES);
        sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");

        return sendSmsRequest;
    }
}
